"use client";
import React, { memo, useMemo, useState } from 'react';
import { Handle, NodeToolbar, Position } from 'reactflow';
import { Label } from '../components/ui/label';
import { Copy, Info, Trash2 } from 'lucide-react';
import clsx from 'clsx';
import { BaseURL } from '@/server/flowise/data';
import FormField from './form-field';
import FormDialog from './form-dialog';
import { useDebouncedCallback } from 'use-debounce';
import useReactflowStore from '@/lib/store/useReactflowStore';

export default memo(({ data, selected, isConnectable }: any) => {
    const [originData, setOriginData] = useState<any>(data);
    const { deleteNode, duplicateNode } = useReactflowStore();
    console.log(data);

    // 防抖更新data数据
    const updateNodeInfo = useDebouncedCallback((sourceData: any) => {
        for (const key in sourceData) {
            if (sourceData.hasOwnProperty(key)) {
                data[key] = sourceData[key];
            }
        }
    }, 500);

    // 数据改变
    const onOriginDataChange = (newVal: any, fieldName?: string) => {
        const newData = !!fieldName ? {
            ...originData,
            [fieldName]: {
                ...originData[fieldName],
                ...newVal
            }
        } : {
            ...originData,
            ...newVal
        }
        setOriginData(newData);
        updateNodeInfo(newData)
    }

    // 输入参数显示
    const inputParams = useMemo(() => {
        const showInputParams = (data?.inputParams || []).filter((i: any) => !i.additionalParams) || [];
        return showInputParams.map((item: any) => {
            const { type, name, label, placeholder, optional, rows, step = 0.1, loadMethod, options, credentialNames, acceptVariable } = item;
            // 凭证类型单独处理
            const isCredential = type === 'credential';
            const value = isCredential ? originData?.[name] : originData?.inputs?.[name];
            const setValue = (val: any) => onOriginDataChange({ [name]: val }, isCredential ? undefined : 'inputs');
            return (
                <div className='relative' key={name}>
                    <FormField
                        type={type}
                        required={!optional}
                        placeholder={placeholder}
                        rows={rows}
                        step={step}
                        label={label}
                        options={options}
                        loadMethod={loadMethod}
                        credentialNames={credentialNames}
                        value={value}
                        onChange={setValue}
                    />

                    {
                        acceptVariable && <Handle
                            id={item.id}
                            type="target"
                            position={Position.Left}
                            isConnectable={isConnectable}
                            style={{
                                background: selected ? '#2196f3' : '#9e9e9e',
                                height: 10,
                                width: 10,
                                left: -5
                            }}
                        />
                    }
                </div>
            )
        })
    }, [originData?.inputs, originData?.inputParams]);

    // 输出参数弹窗显示
    const additionalParams = useMemo(() => {
        const params = (originData?.inputParams || []).filter((i: any) => i.additionalParams) || [];
        if (params?.length) {
            return (
                <FormDialog
                    columns={params}
                    value={originData?.inputs}
                    onChange={(val: any) => onOriginDataChange(val, 'inputs')}
                >
                    <div className='px-3'>
                        <div className='cursor-pointer px-3 py-1.5 text-center border rounded-full text-main border-main hover:bg-[#2196f30a]'>Additional Paramters</div>
                    </div>
                </FormDialog>
            )
        }
        return null;
    }, [originData?.inputs, originData?.inputParams]);

    // 输入连接点
    const inputAnchors = useMemo(() => {
        return (originData?.inputAnchors || []).map((item: any) => {
            return <div className='relative px-3 py-4 rounded-xl' key={item.id}>
                <div className='flex items-center gap-1 text-sm'>
                    <Label className='text-[#666]'>{item.label}</Label>
                    {!item.optional && <span className='text-[#f44336]'>*</span>}
                </div>
                <Handle
                    id={item.id}
                    type="target"
                    position={Position.Left}
                    isConnectable={isConnectable}
                    style={{
                        background: selected ? '#2196f3' : '#9e9e9e',
                        height: 10,
                        width: 10,
                        left: -5
                    }}
                />
            </div>
        })
    }, [originData?.inputAnchors, selected]);

    // 输出连接点
    const outputAnchors = useMemo(() => {
        return (originData?.outputAnchors || []).map((item: any) => {
            const { type, name, label, placeholder, rows, step = 0.1, loadMethod, options, credentialNames } = item;
            return <div className='relative rounded-xl text-right py-4' key={item.id + item.label}>
                <FormField
                    type={type}
                    placeholder={placeholder}
                    rows={rows}
                    step={step}
                    label={label}
                    showLabel={false}
                    options={options}
                    loadMethod={loadMethod}
                    credentialNames={credentialNames}
                    value={originData.outputs[name]}
                    onChange={(val: any) => onOriginDataChange({ [name]: val }, 'outputs')}
                />
                <Handle
                    id={item.id}
                    type="source"
                    position={Position.Right}
                    isConnectable={isConnectable}
                    style={{
                        background: selected ? '#2196f3' : '#9e9e9e',
                        height: 10,
                        width: 10,
                        left: 'auto',
                        right: -5
                    }}
                />
            </div>
        })
    }, [originData?.outputs, originData?.outputAnchors, selected]);

    return <>
        <div className='relative'>
            <NodeToolbar position={Position.Right} align='start'>
                <div className='flex flex-col px-2.5 py-2 bg-white rounded-md border gap-2 shadow-xl'>
                    <span className='group p-1.5 cursor-pointer hover:rounded-full hover:bg-[#f1f1f1]' title='复制' onClick={() => duplicateNode(data.id)}>
                        <Copy className='w-4 h-4 text-[#666] group-hover:text-[#2196f3] ' />
                    </span>
                    <span className='group p-1.5 cursor-pointer hover:rounded-full hover:bg-[#f1f1f1]' title='删除' onClick={() => deleteNode(data.id)}>
                        <Trash2 className='w-4 h-4 text-[#666] group-hover:text-[#f44336]' />
                    </span>
                    <span className='group p-1.5 cursor-pointer hover:rounded-full hover:bg-[#f1f1f1]' title='信息'>
                        <Info className='w-4 h-4 text-[#666] group-hover:text-[#673ab7]' />
                    </span>
                </div>
            </NodeToolbar>
            <div className={clsx(['w-[280px] shadow-md bg-white rounded-xl border cursor-grap hover:border-[#2196f3]', selected ? 'border-[#2196f3]' : 'border-[#616161]'])}>
                <div className='flex items-center px-3 py-2'>
                    <img src={`${BaseURL}/api/v1/node-icon/${data.name}`} className='w-7 h-8 mr-2' alt="" />
                    <div className='text-base'>{data?.label}</div>
                </div>
                <div className='text-sm text-center bg-[#f5f5f5] py-2'>Inputs</div>
                <div className='flex flex-col justify-start'>
                    {inputAnchors}
                </div>
                <form className="flex flex-col gap-5 py-3 w-full text-left">
                    {inputParams}
                    {additionalParams}
                </form>
                <div className='text-sm text-center bg-[#f5f5f5] py-2'>Output</div>
                <div className='flex flex-col'>
                    {outputAnchors}
                </div>
            </div>
        </div>
    </>
});
